package com.cbtx.module.base;

import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/6/10 6:12 PM
 * desc   :
 */
public class MD5Util {

    private static final String TAG = "MD5Util";

    /**
     * 默认的密码字符串组合，用来将字节转换成 16 进制表示的字符
     */
    protected static MessageDigest sMessageDigest = null;

    static {
        try {
            sMessageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    public static String getStringMD5(String str) {
        byte[] buffer = str.getBytes();
        sMessageDigest.update(buffer);
        return byteToHex(sMessageDigest.digest());
    }


    public static String getFileMD5(File file) {
        String md5 = "";
        if (file.exists() && file.isFile()) {
            try (InputStream in = new FileInputStream(file)) {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] buffer = new byte[1024];
                int read;
                while ((read = in.read(buffer)) != -1) {
                    md.update(buffer, 0, read);
                }
                byte[] data = md.digest();
                md5 = byteToHex(data);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        }
        return md5;
    }


    private static String byteToHex(byte[] bytes) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuffer stringbuffer = new StringBuffer(2 * bytes.length);
        for (byte b : bytes) {
            char c0 = hexDigits[b >>> 4 & 0xf];
            char c1 = hexDigits[b & 0xf];
            stringbuffer.append(c0);
            stringbuffer.append(c1);
        }
        return stringbuffer.toString();
    }
}
